//
//  TextInputVC.m
//  XV
//
//  Created by apple on 27/05/2019.
//  Copyright © 2019 XR. All rights reserved.
//

#import "TextInputVC.h"
#import "SVProgressHUD.h"
#import "UITextView+YLTextView.h"


@interface TextInputVC ()


@property (nonatomic, strong) UITextField *textField;
@property (nonatomic, strong) UITextView *textView;
@property (nonatomic, strong) UILabel *countLabel;


@end

@implementation TextInputVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setup];
    [self setupUI];
    self.isAutoClose = YES;
}

-(void)setupUI
{
    _textView.hidden = !_isShowTextView;
    _textField.hidden = _isShowTextView;
    if (_isShowTextView)
    {
        if ( !kStringIsEmpty(self.defalutPlaceholder) ) {
            self.textView.placeholder = self.defalutPlaceholder;
        }
        
        if ( !kStringIsEmpty(self.defalutText) ) {
            self.textView.text = self.defalutText;
        }
        
        [self.textView becomeFirstResponder];
    }
    else
    {
        if ( !kStringIsEmpty(self.defalutPlaceholder) ) {
            self.textField.placeholder = self.defalutPlaceholder;
        }
        
        if ( !kStringIsEmpty(self.defalutText) ) {
            self.textField.text = self.defalutText;
        }
        
        [self.textField becomeFirstResponder];
    }
    
    
    _countLabel.hidden = !_isShowCountLabel;
    _countLabel.text = [NSString stringWithFormat:@"0/%ld",self.max_len];
}

-(void)setup
{
    self.view.backgroundColor = TableViewBGColor;
    
    [self.view addSubview:self.textField];
    [self.view addSubview:self.textView];
    [self.view addSubview:self.countLabel];
    
    [_textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(5);
        make.right.mas_equalTo(-5);
        make.top.mas_equalTo(LL_StatusBarAndNavigationBarHeight+10);
        make.height.mas_equalTo(44);
    }];
    
    [_textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(5);
        make.right.mas_equalTo(-5);
        make.top.mas_equalTo(LL_StatusBarAndNavigationBarHeight+10);
        make.height.mas_equalTo(120);
    }];
    _textView.hidden = YES;
    
    [_countLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-LeadingTrailingMargin);
        make.top.equalTo(_textView.mas_bottom).offset(15);
    }];
    _countLabel.hidden = YES;
    
    NSString* str = kStringIsEmpty(self.rightText) ? @"保存" : self.rightText;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:str style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonDidClick)];
    //UIBarButtonItem字体颜色
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor blackColor];
}

- (void)rightBarButtonDidClick
{
    NSString* text = self.textField.text;
    
    if (self.isShowTextView)
    {
        text = self.textView.text;
    }
    
    if (kStringIsEmpty(text))
    {
        [SVProgressHUD showErrorWithStatus:@"输入内容不能为空"];
        return;
    }
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(TextInputVCDidSave: vc:)])
    {
        [self.delegate TextInputVCDidSave:text vc:self];
    }
    
    if (self.isAutoClose)
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFieldEditChanged:) name:@"UITextFieldTextDidChangeNotification"
                                              object:self.textField];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textViewEditChanged:) name:@"UITextViewTextDidChangeNotification"
                                              object:self.textView];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"UITextFieldTextDidChangeNotification" object:self.textField];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"UITextViewTextDidChangeNotification" object:self.textView];
}

#pragma mark - Notification Method
-(void)textFieldEditChanged:(NSNotification *)obj
{
    UITextField *textField = (UITextField *)obj.object;
    NSString *toBeString = textField.text;
    
    //获取高亮部分
    UITextRange *selectedRange = [textField markedTextRange];
    UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
    
    // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
    if (!position)
    {
        if (toBeString.length > _max_len)
        {
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:_max_len];
            if (rangeIndex.length == 1)
            {
                textField.text = [toBeString substringToIndex:_max_len];
            }
            else
            {
                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, _max_len)];
                textField.text = [toBeString substringWithRange:rangeRange];
            }
        }
    }
}

#pragma mark - Notification Method
-(void)textViewEditChanged:(NSNotification *)obj
{
    UITextView *textView = (UITextView *)obj.object;
    NSString *toBeString = textView.text;
    
    //获取高亮部分
    UITextRange *selectedRange = [textView markedTextRange];
    UITextPosition *position = [textView positionFromPosition:selectedRange.start offset:0];
    
    // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
    if (!position)
    {
        if (toBeString.length > _max_len)
        {
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:_max_len];
            if (rangeIndex.length == 1)
            {
                textView.text = [toBeString substringToIndex:_max_len];
            }
            else
            {
                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, _max_len)];
                textView.text = [toBeString substringWithRange:rangeRange];
            }
        }
    }
    
    if (self.isShowCountLabel)
    {
        _countLabel.text = [NSString stringWithFormat:@"%ld/%ld",textView.text.length,self.max_len];
    }
}


#pragma mark - getter

- (UITextField *)textField {
    if (_textField == nil) {
        _textField = [[UITextField alloc]init];
        _textField.keyboardType = UIKeyboardTypeDefault;
        _textField.placeholder = @"";
        _textField.textColor = ColorHex(0x666666);
        _textField.font = [UIFont systemFontOfSize:13];
        _textField.backgroundColor = [UIColor whiteColor];
        _textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        [_textField setAutocapitalizationType:UITextAutocapitalizationTypeNone];
        //屏蔽系统摇一摇出现的那个撤销弹窗，防止闪退
        [_textField.undoManager removeAllActions];
    }
    return _textField;
}

- (UITextView *)textView {
    if (_textView == nil) {
        _textView = [[UITextView alloc]init];
        _textView.keyboardType = UIKeyboardTypeDefault;
        _textView.textColor = ColorHex(0x666666);
        _textView.font = [UIFont systemFontOfSize:13];
        _textView.backgroundColor = [UIColor whiteColor];
        [_textView setAutocapitalizationType:UITextAutocapitalizationTypeNone];
        //屏蔽系统摇一摇出现的那个撤销弹窗，防止闪退
        [_textView.undoManager removeAllActions];
    }
    return _textView;
}

- (UILabel *)countLabel {
    if (_countLabel == nil) {
        _countLabel = [[UILabel alloc]init];
        _countLabel.textColor = ColorHex(0x666666);
        _countLabel.font = [UIFont systemFontOfSize:13];
        _countLabel.text = @"100字以内";
    }
    return _countLabel;
}

@end
